from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice
from django.core.handlers.wsgi import WSGIRequest
from django.shortcuts import get_object_or_404


# Create your views here.

def index(request: WSGIRequest):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    return render(request, 'polls/index.html', locals())


def detail(request: WSGIRequest, question_id):
    # try:
    #     question = Question.objects.get(id=question_id)
    # except Question.DoesNotExist:
    #     from django.http import Http404
    #     raise Http404('Question {} does not exist'.format(question_id))
    error_message = ''
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', locals())


def results(request: WSGIRequest, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', locals())


def vote(request: WSGIRequest, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(id=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html',
                      {'question': question, 'error_message': "You didn't select a choice."})
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
